package com.sywl.ytcx.config;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.Date;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {
/**
 * 全局异常处理
 * **/

    // 1. 处理404错误
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<Map<String, Object>> handleNotFound(NoHandlerFoundException ex, WebRequest request) {
        return buildErrorResponse(HttpStatus.NOT_FOUND, "资源未找到: " + ex.getRequestURL()+" 请检查路径是否正确", request);
    }

    // 2. 处理所有其他异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleAllExceptions(Exception ex, WebRequest request) {
        ex.printStackTrace();
        return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "服务器处理请求时出错", request);
    }

    // 构建统一错误响应
    private ResponseEntity<Map<String, Object>> buildErrorResponse(
            HttpStatus status, String message, WebRequest request) {

        Map<String, Object> body = Map.of(
                "title","ytcx.space 感谢您的访问，但该路径让我们出错了，感谢一路陪伴",
                "timestamp", new Date(),
                "status", status.value(),
                "error", status.getReasonPhrase(),
                "message", message,
                "path", getRequestPath(request)
        );

        return new ResponseEntity<>(body, status);
    }

    // 获取请求路径
    private String getRequestPath(WebRequest request) {
        String path = request.getDescription(false);
        if (path.startsWith("uri=")) {
            return path.substring(4);
        }
        return path;
    }
}